package edu.xhu.test;

import edu.xhu.api.id.IdClient;
import edu.xhu.model.common.constants.CheckConstants;
import edu.xhu.model.common.dtos.ResponseResult;
import edu.xhu.model.common.enums.IsFlagEnum;
import edu.xhu.model.video.enums.CreateType;
import edu.xhu.model.video.enums.VideoAuth;
import edu.xhu.model.video.enums.VideoStatus;
import edu.xhu.model.video.enums.VideoType;
import edu.xhu.model.video.pojos.*;
import edu.xhu.oss.utils.BiliOssUtils;
import edu.xhu.utils.thread.BiliUserThreadLocalUtil;
import edu.xhu.video.BiliVideoApplication;
import edu.xhu.video.mapper.BiliVideoDataMapper;
import edu.xhu.video.mapper.BiliVideoMapper;
import edu.xhu.video.service.VideoCheckService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

@SpringBootTest(classes = BiliVideoApplication.class)
@RunWith(SpringRunner.class)
public class addDataToVideo {

    @Autowired
    private BiliVideoMapper biliVideoMapper;

    @Autowired
    private IdClient idClient;

    @Autowired
    private BiliVideoDataMapper biliVideoDataMapper;

    @Autowired
    private BiliOssUtils biliOssUtils;





    @Test
    public void addBiliVideo() {

        for(int i=0;i<75;++i){
            BiliVideo video = new BiliVideo();
            BiliVideoData videoData = new BiliVideoData();
            long id = Long.parseLong(idClient.getSnowflakeDistributedId().getData().toString());
            video.setVideoId(id);
            video.setUserId(274227962746765312L);
            video.setTitle("测试视频"+i);
            String code = CreateType.SELF_MADE.getCode();
            video.setCreateType("0");
            video.setAuth(VideoAuth.NO_STATEMENT.getCode());
            video.setVideoType(VideoType.COMMON.getCode());
            video.setState(VideoStatus.PASS.getCode());
            video.setSubChannelId(1L);
            video.setTags("西华,st,点赞,跳水");
            video.setDescription("这是一段测试视频"+i);
            video.setCoverUrl("https://bili-image.oss-cn-hangzhou.aliyuncs.com/%E3%80%90%204%20%E6%9C%88%20%E6%96%B0%20%E7%95%AA%20%EF%BC%9F%E3%80%91%20%E9%92%89%20%E9%92%89%20%E5%8A%A8%20%E7%94%BB%20%E5%8C%96%20%E5%86%B3%20%E5%AE%9A%20%EF%BC%81%20%EF%BC%81.jpg");
            video.setVideoUrl("https://bili-video.oss-cn-hangzhou.aliyuncs.com/%5BLPL%E6%98%A5%E5%AD%A3%E8%B5%9B%5D3%E6%9C%8823%E6%97%A5RNGvsIG.mp4");
            video.setCreateTime(LocalDateTime.now());
            video.setDeleteTime(null);
            video.setDuration(5000L);
            video.setIsCompilation(i%2==0?IsFlagEnum.NO.getCode():IsFlagEnum.YES.getCode());
            video.setIsTop(i%2==0?IsFlagEnum.NO.getCode():IsFlagEnum.YES.getCode());
            video.setUpdateEpisode(2);
            video.setEpisodeTime("周一");
            video.setCoverPathUrl("2018英雄联盟配音秀，刀妹开口，全场震撼，重燃我的LOL斗志！.jpg");
            video.setVideoPathUrl("[LPL春季赛]3月23日RNGvsIG.mp4");
            biliVideoMapper.insert(video);

            videoData.setVideoId(id);
            Random random = new Random();
            Long min = 0L;
            Long max = 20000L;
            Long randomLong = Math.abs(random.nextLong()) % (max - min + 1) + min;
            videoData.setPlay(randomLong);
            videoData.setDanmu(randomLong);
            videoData.setLikes(randomLong);
            videoData.setCoin(randomLong);
            videoData.setCollect(randomLong);
            videoData.setShares(randomLong);
            videoData.setComments(randomLong);
            videoData.setUpdateTime(LocalDateTime.now());
            biliVideoDataMapper.insert(videoData);
        }
    }



    @Test
    public void upladBiliVideo() {

        String videoFolderPath = "E:\\bilibili\\bili-videodata\\data";
        String imageFolderPath = "E:\\bilibili\\bili-videodata\\images";

        String dataFilePath = "E:\\bilibili\\bili-videodata\\xlsxdata\\bilivideo_data_plus.xlsx";
        HashMap <String, BiliVideoUploadData> videoMap = new HashMap<>();
        try (FileInputStream fis = new FileInputStream(dataFilePath);
             Workbook workbook = new XSSFWorkbook(fis);
             Workbook outputWorkbook = new XSSFWorkbook()) {

            // 读取原始Excel文件

            Sheet sheet = workbook.getSheetAt(0);

            // 遍历每一行，假设第一行为标题行
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    Cell titleCell = row.getCell(1);  // 假设第二列是视频标题

                    if (titleCell != null) {
                        String videoTitle = titleCell.getStringCellValue();
                        // 假设你有一个方法来创建一个BiliVideoData对象
                        BiliVideoUploadData videoData = new BiliVideoUploadData();
                        videoData.setPlay((long)(row.getCell(4).getNumericCellValue()));
                        videoData.setDanmu((long)row.getCell(5).getNumericCellValue());
                        videoData.setLikes((long)(row.getCell(6).getNumericCellValue()));
                        videoData.setCoin((long)(row.getCell(7).getNumericCellValue()));
                        videoData.setCollect((long)(row.getCell(8).getNumericCellValue()));
                        videoData.setShares((long)(row.getCell(9).getNumericCellValue()));
                        videoData.setComments((long)(row.getCell(10).getNumericCellValue()));
                        videoData.setVideoSign(row.getCell(12).getStringCellValue());
                        videoData.setSubChannel(row.getCell(13).getStringCellValue());
                        videoData.setDescribation(row.getCell(14).getStringCellValue());
                        videoData.setUpdateTime(LocalDateTime.parse(row.getCell(15).getStringCellValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        String timeString=row.getCell(16).getStringCellValue();
                        String[] parts = timeString.split(":");
                        // 将XX和YY转换为整数
                        int XX = Integer.parseInt(parts[0]);
                        int YY = Integer.parseInt(parts[1]);
                        videoData.setTime(Long.valueOf(60 * XX + YY));
                        videoMap.put(videoTitle, videoData);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 获取视频文件夹中的所有文件
        File videoFolder = new File(videoFolderPath);
        File[] videoFiles = videoFolder.listFiles((dir, name) -> name.endsWith(".mp4")); // 假设视频文件格式为.mp4
        if (videoFiles != null) {
            for (File videoFile : videoFiles) {
                // 查找对应的图片文件
                String imageName = videoFile.getName().replace(".mp4", ".jpg"); // 假设图片格式为.jpg
                File imageFile = new File(imageFolderPath, imageName);

                if (imageFile.exists()) {
                    BiliVideoUploadData videoData = new BiliVideoUploadData();
                    videoData=videoMap.get(videoFile.getName().replace(".mp4", ""));
                    Long userId = 2287248970887168L;
                    String coverUrl = biliOssUtils.uploadImageFile(imageName, imageFolderPath+"\\"+imageName);
                    String videoUrl = biliOssUtils.uploadVideoFile(videoFile.getName(),videoFolderPath+"\\"+videoFile.getName());


                    String coverPathUrl = "/bili-image/" + coverUrl.split("/")[3];
                    String videoPathUrl = "/bili-video/" + videoUrl.split("/")[3];


                    String description = videoData.getDescribation();
                    if (description.length() > 2000) {
                        description = description.substring(0, 2000);
                    }


                    Long videoId = Long.parseLong(idClient.getSnowflakeDistributedId().getData().toString());
                    BiliVideo biliVideo = new BiliVideo()
                            .setVideoId(videoId)
                            .setUserId(userId)
                            .setTitle(videoFile.getName().replace(".mp4", ""))
                            .setCreateType(CreateType.SELF_MADE.getCode())
                            .setAuth(VideoAuth.NO_STATEMENT.getCode())
                            .setVideoType(VideoType.COMMON.getCode())
                            .setState(VideoStatus.CHECK.getCode())
                            .setSubChannelId(1L)
                            .setTags(videoData.getVideoSign())
                            .setDescription(description)
                            .setCoverUrl(coverUrl)
                            .setVideoUrl(videoUrl)
                            .setCreateTime(videoData.getUpdateTime())
                            .setDeleteTime(null)
                            .setDuration(videoData.getTime())
                            .setIsCompilation("0")
                            .setIsTop("0")
                            .setUpdateEpisode(0)
                            .setEpisodeTime("周一")
                            .setCoverPathUrl(coverPathUrl)
                            .setVideoPathUrl(videoPathUrl);
                    BiliVideoData biliVideoData=new BiliVideoData()
                            .setVideoId(videoId)
                            .setPlay(videoData.getPlay())
                            .setDanmu(videoData.getDanmu())
                            .setLikes(videoData.getLikes())
                            .setCoin(videoData.getCoin())
                            .setCollect(videoData.getCollect())
                            .setShares(videoData.getShares())
                            .setComments(videoData.getComments())
                            .setUpdateTime(LocalDateTime.now());
                    try {
                        biliVideoMapper.insert(biliVideo);
                        biliVideoDataMapper.insert(biliVideoData);
                    } catch (Exception e) {
                        System.out.println("Error occurred while inserting data: " + e.getMessage());
                        continue;
                    }


                    System.out.println("Uploaded: " + videoFile.getName() + " and " + imageFile.getName());
                } else {
                    System.out.println("Image file not found for video: " + videoFile.getName());
                }
            }
        }
    }
}
